package com.ys.malini.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

//继承自这个接口javax.servlet.Filter;
//在web.xml里配置PagerFilter
public class PagerFilter implements Filter {
	

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		PagerContext.setOffset(getOffset(httpRequest));
		PagerContext.setPagesize(getPagesize(httpRequest));
		
		if(httpRequest.getParameter("pager.offset") == null){
			PagerContext.setTotal(0);
		}
		
//		就不catch了。异常抛出了。
		try{
			//作用是让程序继续往下执行，直到执行完后
			chain.doFilter(request, response);
		}finally{
			//清空ThreadLocal中的值
			PagerContext.removeOffset();
			PagerContext.removePagesize();
		}
		
	}
	
	protected int getOffset(HttpServletRequest request){
		int offset = 0;
		try {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		} catch (NumberFormatException ignore) {
		}
		return offset;
	}
	
//	一般获取pagesize是从session里获得。由用户来设置。
	protected int getPagesize(HttpServletRequest request){
		//return Integer.parseInt(request.getParameter("maxPageItems"));
		return PagerContext.MAX_PAGE_SIZE;
	}

	public void init(FilterConfig arg0) throws ServletException {
	}

}
